/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package zuo.biao.library.ui;



import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import ohos.aafwk.ability.OnClickListener;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.InputAttribute;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.multimodalinput.event.TouchEvent;
import zuo.biao.library.ResourceTable;
import zuo.biao.library.base.BaseAbility;
import zuo.biao.library.interfaces.OnBottomDragListener;
import zuo.biao.library.util.EditTextUtil;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.StringUtil;

/**通用编辑个人资料文本界面
 * @author Lemon
 * @use
 * <br> toActivity或startActivityForResult (EditTextInfoActivity.createIntent(...), requestCode);
 * <br> 然后在onActivityResult方法内
 * <br> data.getStringExtra(EditTextInfoActivity.RESULT_EDIT_TEXT_INFO); 可得到输入框内容
 */
public class EditTextInfoActivity extends BaseAbility implements OnBottomDragListener {
	private static final String TAG = "EditTextInfoActivity";

	//启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	/**
	 * RESULT_TYPE
	 */
	protected static final String RESULT_TYPE = "RESULT_TYPE";
	/**
	 *RESULT_KEY
	 */
	protected static final String RESULT_KEY = "RESULT_KEY";
	/**
	 *RESULT_VALUE
	 */
	protected static final String RESULT_VALUE = "RESULT_VALUE";
	/**
	 *RESULT_URL
	 */
	protected static final String RESULT_URL = "RESULT_URL";
	/**
	 *RESULT_ID
	 */
	protected static final String RESULT_ID = "RESULT_ID";
	/**
	 *RESULT_IMAGE_URL
	 */
	protected static final String RESULT_IMAGE_URL = "RESULT_IMAGE_URL";

	/**
	 * @param context 上下文
	 * @param key key
	 * @param value value
	 * @return Intent
	 */
	public static Intent createIntent(Context context, String key, String value) {
		return createIntent(context, 0, key, value);
	}
	/**
	 * @param context 上下文
	 * @param type 类型
	 * @param key key
	 * @param value value
	 * @return Intent
	 */
	public static Intent createIntent(Context context, int type, String key, String value) {
		Intent intent=new Intent();
		Operation operationBuilder =
				new Intent.OperationBuilder()
						.withAbilityName("zuo.biao.library.ui.EditTextInfoActivity" )
						.withDeviceId("")
						.withFlags(Intent.FLAG_ABILITY_NEW_MISSION)
						.withBundleName(context.getBundleName())
						.build();

		intent.setOperation(operationBuilder);
		intent.setParam(INTENT_TYPE, type);
				intent.setParam(INTENT_KEY, key);
				intent.setParam(INTENT_VALUE, value);

		return intent;
	}

	//启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


	@Override
	protected void onStart(Intent intent) {
		super.onStart(intent);
		setUIContent(ResourceTable.Layout_edittext_info_layout);
		//必须调用<<<<<<<<<<<
		initView();
		initData();
		initEvent();
		//必须调用>>>>>>>>>>
	}



	//UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	private TextField etEditTextInfo;
	private Image ivEditTextInfoClear;
	private Text tvEditTextInfoRemind;
	private ListContainer lvEditTextInfo;
	//	private XListView lvEditTextInfo;
	@Override
	public void initView() {//必须调用

		etEditTextInfo = findView(ResourceTable.Id_etEditTextInfo);
		ivEditTextInfoClear = findView(ResourceTable.Id_ivEditTextInfoClear);
		tvEditTextInfoRemind = findView(ResourceTable.Id_tvEditTextInfoRemind);

		lvEditTextInfo = findView(ResourceTable.Id_lvEditTextInfo);
	}

	private ItemProvider adapter;
	/**显示列表内容
	 * @author author
	 * @param list data
	 */
	private void setList(List<String> list) {
		if (hasList == false || list == null || list.size() <= 0) {
			adapter = null;
			lvEditTextInfo.setItemProvider(null);
			return;
		}

		adapter = new ItemProvider(context, list);
		lvEditTextInfo.setItemProvider(adapter);
		lvEditTextInfo.scrollBy(60, 200);
	}


	//UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>










	//Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	protected static final int TYPE_NICK = EditTextInfoWindow.TYPE_NICK;
	protected static final int TYPE_NAME = EditTextInfoWindow.TYPE_NAME;

	protected static final int TYPE_PHONE = EditTextInfoWindow.TYPE_PHONE;
	protected static final int TYPE_WEBSITE = EditTextInfoWindow.TYPE_WEBSITE;
	protected static final int TYPE_EMAIL = EditTextInfoWindow.TYPE_EMAIL;
	protected static final int TYPE_FAX = EditTextInfoWindow.TYPE_FAX;

	protected static final int TYPE_USUALADDRESS = EditTextInfoWindow.TYPE_USUALADDRESS;
	protected static final int TYPE_MAILADDRESS = EditTextInfoWindow.TYPE_MAILADDRESS;
	protected static final int TYPE_SCHOOL = EditTextInfoWindow.TYPE_SCHOOL;
	protected static final int TYPE_COMPANY = EditTextInfoWindow.TYPE_COMPANY;

	protected static final int TYPE_PROFESSION = EditTextInfoWindow.TYPE_PROFESSION;
	protected static final int TYPE_NOTE = EditTextInfoWindow.TYPE_NOTE;
	//	public static final int TYPE_OTHER = EditTextInfoWindow.TYPE_OTHER;

	protected static final String INTENT_TYPE = EditTextInfoWindow.INTENT_TYPE;
	protected static final String INTENT_KEY = EditTextInfoWindow.INTENT_KEY;
	protected static final String INTENT_VALUE = EditTextInfoWindow.INTENT_VALUE;

	private int intentType = 0;
	private int maxEms = 30;
	private boolean hasList = false;
	private boolean hasUrl = false;

	private ArrayList<String> list;
	@Override
	public void initData() {//必须调用
		intent = getIntent();

		intentType = intent.getIntParam(INTENT_TYPE, 0);
		if (StringUtil.isNotEmpty(intent.getStringParam(INTENT_KEY), true)) {
			tvBaseTitle.setText(StringUtil.getCurrentString());
		}
		etEditTextInfo.setMultipleLine(intentType != TYPE_NOTE);

		switch (intentType) {
		case TYPE_NICK:
			maxEms = 20;
			break;
		case TYPE_PHONE:
			etEditTextInfo.setTextInputType(InputAttribute.PATTERN_NUMBER);
			maxEms = 11;
			break;
		case TYPE_EMAIL:
			etEditTextInfo.setTextInputType(InputAttribute.PATTERN_TEXT);
			maxEms = 60;
			break;
		case TYPE_WEBSITE:
			etEditTextInfo.setTextInputType(InputAttribute.PATTERN_TEXT);
			maxEms = 200;
			break;
		case TYPE_MAILADDRESS:
			maxEms = 60;
			break;
		case TYPE_PROFESSION:
			tvEditTextInfoRemind.setText("所属行业");
			maxEms = 15;
		case TYPE_NOTE:
			maxEms = 100;
			break;
		default:
			break;
		}
		etEditTextInfo.setMaxTextLines(maxEms);
		tvEditTextInfoRemind.setText("限" + maxEms/2 + "个字（或" + maxEms + "个字符）");


		getList(intentType);
	}

	private int requestSize = 20;
	/**获取列表
	 * @author lemon
	 * @param listType listType
	 * @return getList
	 */
	protected void getList(final int listType) {
		if (hasList == false) {
			return;
		}

		list = new ArrayList<String>();
		runThread(TAG + "getList", new Runnable() {
			@Override
			public void run() {
				if (listType == TYPE_PROFESSION) {
					list = new ArrayList<String>();
					list.add("计算机");
					list.add("会计");
					list.add("商业");
					list.add("贸易");
					list.add("生产");
					list.add("医疗");
					list.add("文化");
					list.add("娱乐");
					list.add("公务员");
					list.add("房地产");
					list.add("律师");
					list.add("教育");
					list.add("学生");
				}

				runUiThread(new Runnable() {
					@Override
					public void run() {
						dismissProgressDialog();
						if (hasList) {
							setList(list);
						}
					}
				});
			}
		});
	}

	private void saveAndExit() {
		String editedValue = StringUtil.getTrimedString(etEditTextInfo);
		if (editedValue.equals("" + getIntent().getStringParam(INTENT_VALUE))) {
			showShortToast("内容没有改变哦~");
		} else {
			intent = new Intent();
			intent.setParam(RESULT_TYPE, getIntent().getIntParam(INTENT_TYPE, -1));
			//				intent.putExtra(RESULT_TYPE, StringUtil.getTrimedString(etEditTextInfo));
			//				intent.putExtra(RESULT_KEY, StringUtil.getTrimedString(etEditTextInfo));
			intent.setParam(RESULT_VALUE, editedValue);
			setResult(-1, intent);

			terminateAbility();
		}
	}

	//Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>








	//Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	private String inputedString;

	private static final long SEARCH_DELAY_TIME = 240;
	private EventHandler searchHandler;
	@Override
	public void initEvent() {//必须调用
		searchHandler = new EventHandler(EventRunner.getMainEventRunner()){
			@Override
			protected void processEvent(InnerEvent event) {
				super.processEvent(event);
				if (event == null) {
					return;
				}
				if(inputedString != null){
					if (inputedString.equals(event.object)) {
						getList(intentType);
					}
				}
			}
		};

		etEditTextInfo.addTextObserver(new Text.TextObserver() {
			@Override
			public void onTextUpdated(String s, int i, int i1, int i2) {
				inputedString = StringUtil.getTrimedString(s);
				if (StringUtil.isNotEmpty(inputedString, true) == false) {
					ivEditTextInfoClear.setVisibility(Component.HIDE);
				} else {
					ivEditTextInfoClear.setVisibility(Component.VISIBLE);
					if (hasUrl == true) {
						InnerEvent innerEvent = InnerEvent.get();
						innerEvent.object = inputedString;

						searchHandler.sendEvent(innerEvent , SEARCH_DELAY_TIME);
					}
				}
			}
		});
		ivEditTextInfoClear.setClickedListener(new Component.ClickedListener() {
			@Override
			public void onClick(Component component) {
				etEditTextInfo.setText("");
			}
		});


		etEditTextInfo.setText(StringUtil.getTrimedString(getIntent().getStringParam(INTENT_VALUE)));

		if (hasList == true) {

			if (hasUrl) {
			}
			lvEditTextInfo.setItemClickedListener(new ListContainer.ItemClickedListener() {
				@Override
				public void onItemClicked(ListContainer listContainer, Component component, int position, long l) {
					if (position < adapter.getCount()) {
						etEditTextInfo.setText("" + adapter.getItem(position));
						if (hasUrl) {
							intent = new Intent();
							intent.setParam(RESULT_TYPE, getIntent().getIntParam(INTENT_TYPE, -1));
							intent.setParam(RESULT_KEY, getIntent().getStringParam(INTENT_KEY));
							intent.setParam(RESULT_VALUE, adapter.getItem(position).toString());
							setResult(-1, intent);
							terminateAbility();
							return;
						}
						saveAndExit();
					}
				}
			});

		}

	}

	@Override
	public void onDragBottom(boolean rightToLeft) {
		if (rightToLeft) {
			saveAndExit();
			return;
		}
		terminateAbility();
	}


	//系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	//类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<



	//类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

	//系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


	//Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>








	//内部类,尽量少用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<



	//内部类,尽量少用>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

}